package org.aplombh.java.leetcode.all;

public class _6Z字形变换 {
    public static void main(String[] args) {
//        System.out.println((int) (1.0 * 14 / (3 + (3 - 2)) + 0.5));
        System.out.println(new Solution6_1().convert("PAYPALISHIRING", 4));
    }
}

// 二维矩阵模拟
class Solution6_1 {
    public String convert(String s, int numRows) {
        if (numRows <= 1)
            return s;
        // 每列相差
        int d = numRows - 2 + 1;
        // 每个z中字符的个数
        int n = numRows + (numRows - 2);
        // 一共占用多少列
        int m = d * (s.length() / n + ((s.length() % n) == 0 ? 0 : 1));
        char[][] chars = new char[numRows][m];

        for (int i = 0; i < s.length(); i++) {
            // 第几个z
            int p = i / n;
            // z中的第几个
            int q = i % n;

            if (q < numRows) {
                chars[q][p * d] = s.charAt(i);
            } else {
                chars[numRows - (q - numRows + 1) - 1][p * d + (d - (q - numRows)) - 1] = s.charAt(i);
            }

        }
        StringBuffer sb = new StringBuffer();
        for (char[] aChar : chars) {
            for (char c : aChar) {
                if (c != '\u0000')
                    sb.append(c);
            }
        }
        return sb.toString();
    }
}

// 添加多个队列numRows个队列,每次遍历向后面添加
class Solution6_2 {
    public String convert(String s, int numRows) {
        if (numRows <= 1)
            return s;

        int n = numRows + (numRows - 2);

        StringBuffer[] buffers = new StringBuffer[numRows];
        for (int i = 0; i < numRows; i++) {
            buffers[i] = new StringBuffer();
        }

        for (int i = 0, p = 0; i < s.length(); i++) {

            buffers[p].append(s.charAt(i));
            if (i % n < numRows - 1) p++;
            else p--;

        }
        StringBuilder ans = new StringBuilder();
        for (StringBuffer row : buffers) {
            ans.append(row);
        }
        return ans.toString();
    }
}

// 每次找到当前周期中的第一个元素
class Solution6_3 {
    public String convert(String s, int numRows) {
        if (numRows <= 1)
            return s;

        int n = numRows + (numRows - 2);
        StringBuffer ans = new StringBuffer();
        // 矩阵的每一行
        for (int i = 0; i < numRows; ++i) {
            // 当前行应该包含的所有数据
            for (int j = 0; j < n; j++) {
                //TODO
            }
        }

        return ans.toString();
    }
}

